package com.hyrluntan.forum.controller;

import com.hyrluntan.forum.common.AppResult;
import com.hyrluntan.forum.common.ResultCode;
import com.hyrluntan.forum.config.AppConfig;
import com.hyrluntan.forum.model.Message;
import com.hyrluntan.forum.model.User;
import com.hyrluntan.forum.services.IMessageService;
import com.hyrluntan.forum.services.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@Api(tags = "站内信接⼝")
@RestController
@RequestMapping("/message")
public class MessageController {
    // 注⼊业务层
    @Resource
    private IMessageService messageService;
    @Resource
    private IUserService userService;

    /**
     * 发送站内信
     *
     * @param receiveUserId 接收用户id
     * @param content 内容
     * @return AppResult
     */
    @ApiOperation("发送站内信")
    @PostMapping("/send")
    public AppResult send (HttpServletRequest request,
                           @ApiParam(value = "接收⽤⼾Id") @RequestParam(value = "receiveUserId") @NonNull Long receiveUserId,
                           @ApiParam(value = "站内信内容") @RequestParam(value = "content") @NonNull String content) {
        // 获取发送⽤⼾信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 判断是否被禁⾔,禁言状态不能发送站内信
        if (user.getState() != 0) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString() + ", userId = " + user.getId());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 不能给⾃⼰发送
        if (user.getId() == receiveUserId) {
            log.warn("不能给⾃⼰发送站内信. postUserId = " + user.getId() + ", receiveUserId = " + receiveUserId);
            return AppResult.failed(ResultCode.FAILED_CREATE);
        }
        // 查询接收⽤⼾
        User receiveUser = userService.selectById(receiveUserId);
        if (receiveUser == null || receiveUser.getDeleteState() != 0) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + ", receiveUserId = " + receiveUserId);
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        // 构造对象
        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(receiveUserId);
        message.setContent(content);
        messageService.create(message);
        return AppResult.success();
    }

    /**
     * 获取未读消息个数
     *
     * @return AppResult<Integer>
    **/
    @ApiOperation("获取未读消息个数")
    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount (HttpServletRequest request) {
        // 获取发送⽤⼾信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        Integer result = messageService.selectUnreadCount(user.getId());
        return AppResult.success(result);
    }

    /**
     * 查询用户的所有站内信
     *
     * @return 站内信集合
     */
    @ApiOperation("查询⽤⼾的所有站内信")
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAll(HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 获取⽤⼾站内信
        List<Message> result = messageService.selectByReceiveUserId(user.getId());
        return AppResult.success(result);
    }

    /**
     * 更新状态为已读
     *
     * @param id 站内信Id
     * @return AppResult<Message>
     */
    @ApiOperation("更新状态为已读")
    @PostMapping("/markRead")
    public AppResult markRead (HttpServletRequest request,
                               @ApiParam(value = "站内信Id") @RequestParam(value = "id") @NonNull Long id) {
        // 根据Id查询站内信
        Message message = messageService.selectById(id);
        if(message==null||message.getDeleteState()==1){
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 接收⽅不是⾃⼰
        if (user.getId() != message.getReceiveUserId()) {
            log.warn("查询了不属于⾃⼰的站内信：userId = " + user.getId() + ", receiveUserId = " + message.getReceiveUserId());
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        // 更新为已读状态
        messageService.updateStateById(id, (byte)1);
        return AppResult.success();
    }

    /**
     * 回复站内信
     * @param repliedId 要回复的站内信Id
     *  @param content 站内信的内容
     * @return AppResult
     */
    @ApiOperation("回复站内信")
    @PostMapping("/reply")
    public AppResult reply (HttpServletRequest request,
                            @ApiParam("要回复的站内信Id") @RequestParam("repliedId") @NonNull Long repliedId,
                            @ApiParam("站内信的内容") @RequestParam("content") @NonNull String content) {
        // 校验当前登录⽤⼾的状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 校验要回复的站内信状态
        Message existsMessage = messageService.selectById(repliedId);
        if (existsMessage == null || existsMessage.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        // 不能给⾃⼰回复
        if (user.getId() == existsMessage.getPostUserId()) {
            return AppResult.failed("不能回复⾃⼰的站内信");
        }
        // 构造对象
        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(existsMessage.getPostUserId());
        message.setContent(content);
        messageService.reply(repliedId, message);
        return AppResult.success();
    }
}
